import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Detail from '../views/Detail.vue'
import VuexDemo from '../views/VuexDemo'
import Cart from '../views/Cart'
import store from '../store/index.js'

Vue.use(VueRouter)
// let isLogin = true  //模拟登录状态
const router = new VueRouter({
    // mode:'history',  //这种模式在部署的时候，会有路由404的问题
    routes:[
        {
            path:'/login',
            component:()=>import ('../views/Login') //路由懒加载
        },
        {
            path:'/reg',
            component:()=>import ('../views/Reg') //路由懒加载
        },
        {
            path:'/',
            component:()=>import ('../views/Main'), //路由懒加载
            children:[
                {
                    path:'home',
                    alias:'/',
                    component:Home
                },
                {
                    path:'detail/:id',
                    component:Detail
                },
                {
                    path:'cart',
                    component:Cart
                },
                {
                    path:'checkout',
                    component:()=>import ('../views/CheckOut') //路由懒加载
                },
                {
                    path:'account',
                    component:()=>import ('../views/Account'), //路由懒加载
                    children:[
                        {
                            path:'address',
                            component:()=>import ('../views/Account/Address')
                        },
                        {
                            path:'order',
                            component:()=>import ('../views/Account/Order')
                        },
                        {
                            path:'setting',
                            component:()=>import ('../views/Account/Setting')
                        }
                    ],
                    // beforeEnter(to,from,next){  //路由独享守卫
                    //     if(isLogin){ //判断登录状态
                    //         next()
                    //     }else{
                    //         next('/login')
                    //     }
                    // }
                },
                
                {
                    path:'cors',
                    component:()=>import ('../views/CorsDemo') //路由懒加载
                },
                {
                    path:'vuex',
                    component:VuexDemo
                }
            ]
        },
    ]
})


router.beforeEach((to,from,next)=>{ //路由的全局前置守卫
    console.log(to,from);
    // path = '/checkout'   '/account'
    if(to.path.indexOf('/account')==-1){ //判断用户访问的是不是个人中心
        next()  //不是个人中心，直接放行
    }else{
        if(store.state.my.userInfo){ //判断登录状态
            next()
        }else{
            next({
                path:'/login',
                query:{
                    target:to.path
                }
            })
        }
    }
})

export default router